package com.example.testinternet;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;

public class ServletActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_servlet);
        Button btnLogin = (Button) findViewById(R.id.btn_login_s);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String ip="http://10.0.2.2:8080/testname/login";
                        try {
                            URL url=new URL(ip);
                            HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                            conn.setConnectTimeout(2000);

                            conn.setRequestMethod("POST");
                            String data="username="+ URLEncoder.encode("tom","utf-8")+
                                    "&password="+URLEncoder.encode("123","utf-8");
                            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                            conn.setRequestProperty("Content-Length",data.length()+"");
                            conn.setDoOutput(true);


                            //if (conn.getResponseCode()==200){
                                OutputStream os=conn.getOutputStream();

                                os.write(data.getBytes());
                            os.flush();
                            Thread.sleep(1000);
                            Log.i("ServletActivity", "code: "+conn.getResponseCode());
                            if (conn.getResponseCode()==200){
                            InputStream is=conn.getInputStream();
                                byte[]buf=new byte[1024];
                                int length=is.read(buf);
                                String resData=new String(buf,0,length);
                                Log.i("ServletActivity", "run: "+resData);
                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }
}
